import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // 引入一份进度条插件
import 'nprogress/nprogress.css' // 引入进度条样式
// 前置导航守卫位置
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const page = ['/login', '/404']
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (!store.getters.getUsername) {
        const { roles } = await store.dispatch('user/getUserInfo')
        // 判断有没有权限查看左侧栏
        const addRouterList = await store.dispatch('permission/fileRouter', roles.menus)
        // 给路由添加动态路由
        router.addRoutes([...addRouterList, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)
      } else {
        next()
      }
    }
  } else {
    if (page.indexOf(to.path) === -1) {
      next('/login')
      Message.error('未登录,请先登录')
    } else {
      next()
    }
    NProgress.done() // 关闭进度条
  }
})

// 后置导航守卫位置
router.afterEach((to, from) => {
  NProgress.done() // 关闭进度条
})
